package com.fs.system.security;

import com.fs.common.core.vo.LoginUser;
import com.fs.system.service.impl.TokenService;
import com.fs.system.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private TokenService  tokenService;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        LoginUser loginUser = tokenService.getLoginUser(request);
        //redis有LoginUser对象,并且SecurityContext上下文中没有Authentication对象
        if(Objects.nonNull(loginUser) && Objects.isNull(SecurityUtils.getAuthentication())){

            //tokenService.verifyToken(loginUser);
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());

            //给认证对象设置请求相关信息
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            //保存到SecurityContext
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);

            //loginUser续期
            //tokenService.refreshToken(loginUser);
            tokenService.verifyToken(loginUser);  //减少对redis访问,降低redis压力
        }

        //放行
        filterChain.doFilter(request,response);
    }
}